/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Parser;

import java.util.ArrayList;
import java.util.Stack;

/**
 * 
 * @author AlinT
 */
public class PostFixForm extends Parser{

    public PostFixForm()
   {
       operatori.add("+"); operatori.add("-"); operatori.add("/"); operatori.add("*");
       operatori.add("sin"); operatori.add("cos");operatori.add("tg");operatori.add("ctg");
       operatori.add("ARCCOS"); operatori.add("ARCCOS"); operatori.add("ARCTG"); operatori.add("ARCCTG");
       operatori.add("EXP"); operatori.add("log"); operatori.add("pow"); operatori.add("sqrt");
       operatori.add("("); operatori.add(")");
       this.oke=true;
   }

   @Override
   /**
    * @see Parser.hasLessPrecedence
    */
   public boolean hasLessPrecedence(String c, String d)
   {
      if(!c.equals("+")&&!c.equals("-")&&!c.equals("*")&&!c.equals("/")&&!c.equals("(")&&!c.equals(")")) c="o";
      if(!d.equals("+")&&!d.equals("-")&&!d.equals("*")&&!d.equals("/")&&!c.equals("(")&&!c.equals(")")) d="o";

      return "(+*o(-/o".indexOf(c)%4 < "(+*o(-/o".indexOf(d)%4;
   }

    @Override
    /**
     * Aceasta functie transforma expresia in foma poloneza postfixata
    * @see Parser.polishForm
    */
    public ArrayList<String> polishForm(ArrayList<String> poz){
      Stack<String> stack = new Stack<String>();
      ArrayList<String> rezultat=new ArrayList<String>();

      int i=0;
      while(i<poz.size())
      {
         String c=poz.get(i);

         if (c.equals("(")) stack.push(c);
         else if (!isOperator(c)){
            if(!c.equals(""))
                rezultat.add(c);
         }
         else if (c.equals(")")){
            while(!stack.empty() && (stack.peek() != "("))
                  rezultat.add(stack.pop());
            if(!stack.empty()) stack.pop();
         }
         else if (isOperator(c) && !c.equals("(") && !c.equals(")")){
            while(!stack.isEmpty() && !hasLessPrecedence(stack.peek(), c))
                   rezultat.add(stack.pop());
            stack.push(c);
         }
         else throw new Error("Invalid operand or operator: "+c);

         i++;
      }
      while (!stack.isEmpty())
          rezultat.add(stack.pop());

      return rezultat;
   }
}
